<?php
//对图片的输入输出的封装.
class TbfImageObj {
    private $gdImg;
    private $_isFileCacheValid = true; //如果什么也没有做,表示文件内容没有变化过,则可以使用原来的文件名
    private $_cacheContent;
    /**
     * 从文件创建,可以使用ext提示文件扩展名(上传的没有文件扩展名)
     * @param string $filepath 可能是url
     * @param string|null $ext
     * @return TbfImageObj
     */
    static function createFromFile($filepath){
        $content = @file_get_contents($filepath);
        if (empty($content)){
            TbfError::unExpect('文件读取错误['.$filepath.']');
            return null;
        }
        $obj = new TbfImageObj();
        $obj->_cacheContent = $content;
        $obj->gdImg = @imagecreatefromstring($content);
        if (empty($obj->gdImg)){
            TbfError::unExpect('图片格式错误');
            return null;
        }
        return $obj;
    }

    /**
     * @param $gdImg
     * @return TbfImageObj
     */
    static function createFromGdImage($gdImg){
        $obj = new TbfImageObj();
        $obj->gdImg = $gdImg;
        $obj->markFileCacheInvalid();
        return $obj;
    }

    function getGdImage(){
        return $this->gdImg;
    }

    //返回图片的内容
    function getImageContent($ext){
        if ($this->_isFileCacheValid){
            return $this->_cacheContent;
        }
        if ($ext==='jpeg' || $ext==='jpg'){
            ob_start();
            imagejpeg($this->gdImg);
            return ob_get_clean();
        }
        if ($ext==='png'){
            ob_start();
            imagepng($this->gdImg);
            return ob_get_clean();
        }
        if ($ext==='gif'){
            ob_start();
            imagegif($this->gdImg);
            return ob_get_clean();
        }
        TbfError::unExpect(sprintf('[TbfImageObj.getImageContent] can not handle ext:[%s]',$ext));
        return '';
    }

    function isFileCacheValid(){
        return $this->_isFileCacheValid;
    }
    function markFileCacheInvalid(){
        $this->_isFileCacheValid = false;
    }
}
